package com.endurance.aop;

import com.endurance.utils.MyCache;
import lombok.extern.slf4j.Slf4j;
import org.aopalliance.intercept.Joinpoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @Author: sunlin
 * @Date: 2024-05-17 8:37
 * @Version: 1.0
 * @Description: 使用AOP技术获取要执行的目标方法
 */
@Aspect
@Slf4j
@Component
public class CacheAop {

    @Autowired
    private MyCache myCache;

    @Around(value = "@annotation(com.endurance.annotation.MyCacheAnnotation)")
    public Object around(ProceedingJoinPoint joinpoint) throws Throwable {
        Signature signature = joinpoint.getSignature();
        MethodSignature methodSignature = (MethodSignature) signature;
        Method method = methodSignature.getMethod();
        // 动态的拼接Key
        String key = method.getName() + Arrays.toString(method.getParameterTypes())
                + Arrays.toString(joinpoint.getArgs());
        return myCache.getCache(key, method.getReturnType(), joinpoint);
    }

}
